package com.zliblike_platform.controller;

import com.zliblike_platform.dto.BookDownloadDTO;
import com.zliblike_platform.dto.BookUploadDTO;
import com.zliblike_platform.dto.FormatConversionDTO;
import com.zliblike_platform.service.BookService;
import com.zliblike_platform.vo.BookInfoVO;
import com.zliblike_platform.vo.BookUploadResultVO;
import com.zliblike_platform.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;

/**
 * 书籍控制器
 */
@RestController
@RequestMapping("/api/book")
public class BookController {

    @Autowired
    private BookService bookService;
    
    /**
     * 获取书籍信息
     */
    @GetMapping("/{bookId}")
    public ResponseResult<BookInfoVO> getBookInfo(@PathVariable Long bookId) {
        BookInfoVO bookInfo = bookService.getBookInfo(bookId);
        if (bookInfo == null) {
            return ResponseResult.fail(4002, "书籍不存在");
        }
        return ResponseResult.success(bookInfo);
    }
    
    /**
     * 获取热门书籍
     */
    @GetMapping("/popular")
    public ResponseResult<List<BookInfoVO>> getPopularBooks(
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        List<BookInfoVO> books = bookService.getPopularBooks(limit);
        return ResponseResult.success(books);
    }
    
    /**
     * 获取分类下的热门书籍
     */
    @GetMapping("/popular/category/{categoryId}")
    public ResponseResult<List<BookInfoVO>> getPopularBooksByCategory(
            @PathVariable Long categoryId,
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        List<BookInfoVO> books = bookService.getPopularBooksByCategory(categoryId, limit);
        return ResponseResult.success(books);
    }
    
    /**
     * 下载电子书
     */
    @GetMapping("/download/{bookId}")
    @PreAuthorize("isAuthenticated()")
    public void downloadBook(
            @PathVariable Long bookId,
            @RequestParam(required = false, defaultValue = "PDF") String format,
            HttpServletResponse response) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 构造下载参数
        BookDownloadDTO downloadDTO = new BookDownloadDTO();
        downloadDTO.setBookId(bookId);
        downloadDTO.setFormat(format);
        
        // 执行下载
        bookService.downloadBook(userId, downloadDTO, response);
        // 注意：这个方法不需要返回ResponseResult，因为它直接写入响应流
    }
    
    /**
     * 获取书籍可用格式
     */
    @GetMapping("/{bookId}/formats")
    public ResponseResult<List<String>> getAvailableFormats(@PathVariable Long bookId) {
        List<String> formats = bookService.getAvailableFormats(bookId);
        return ResponseResult.success(formats);
    }
    
    /**
     * 请求格式转换
     */
    @PostMapping("/convert/{bookId}")
    public ResponseResult<Map<String, Object>> requestFormatConversion(
            @PathVariable Long bookId,
            @RequestBody FormatConversionDTO conversionDTO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 设置书籍ID
        conversionDTO.setBookId(bookId);
        
        // 请求格式转换
        Long convertId = bookService.requestFormatConversion(userId, conversionDTO);
        
        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("convertId", convertId);
        result.put("bookId", bookId);
        result.put("targetFormat", conversionDTO.getTargetFormat());
        result.put("estimatedTime", 120); // 假设转换需要2分钟
        
        return ResponseResult.success("格式转换请求已提交", result);
    }
    
    /**
     * 获取支持的文件格式
     */
    @GetMapping("/supported-formats")
    public ResponseResult<List<String>> getSupportedFormats() {
        List<String> formats = bookService.getFormats();
        return ResponseResult.success(formats);
    }
    
    /**
     * 检查ISBN是否已存在
     */
    @GetMapping("/check-isbn")
    public ResponseResult<Boolean> checkIsbnExists(@RequestParam String isbn) {
        boolean exists = bookService.isbnExists(isbn);
        return ResponseResult.success(exists);
    }
    
    /**
     * 上传电子书
     */
    @PostMapping("/upload")
    @PreAuthorize("isAuthenticated()")
    public ResponseResult<BookUploadResultVO> uploadBook(
            @ModelAttribute BookUploadDTO uploadDTO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 执行上传
        BookUploadResultVO result = bookService.uploadBook(userId, uploadDTO);
        
        if ("成功".equals(result.getStatus())) {
            return ResponseResult.success("上传成功", result);
        } else {
            return ResponseResult.fail(4001, result.getMessage());
        }
    }
    
    /**
     * 获取封面图片
     */
    @GetMapping("/{bookId}/cover")
    public void getBookCover(@PathVariable Long bookId, HttpServletResponse response) {
        // 获取书籍信息
        BookInfoVO bookInfo = bookService.getBookInfo(bookId);
        if (bookInfo == null) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "书籍不存在");
            } catch (Exception e) {
                // 忽略异常
            }
            return;
        }
        
        // TODO: 从数据库或文件系统获取封面图片，设置Content-Type并写入响应流
    }
} 